from flask import Blueprint, render_template, request, session, flash, redirect, url_for,  make_response
from blog.model.UserBase import UserBase
from blog import tools

#  创建蓝图 第一个参数为蓝图的名字
account = Blueprint('account', __name__)


@account.route('/')
def index():
    pass


@account.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('account/login.html')
    if request.method == 'POST':
        error = None
        # strip() 方法用于移除字符串头尾指定的字符（默认为空格）
        username = request.form['username'].strip()
        password = request.form['password'].strip()

        if username == '':
            error = '请输入用户名'
        elif password == '':
            error = '请输入密码'
        else:
            password = tools.str_to_md5(password)  # MD5加密
            user = UserBase.query.filter_by(name=username, password=password).first()
            if user is None:
                error = '用户名或密码错误'
                # app.logger.error('用户名或密码错误')
            else:
                session["username"] = username  # 设置session
                return redirect('/home/index')
                # response = make_response(render_template('account/login.html'))
                # response.set_cookie("username", username, max_age=3600)  # 设置cookie
                # return response

        return render_template('account/login.html', error=error)


@account.route('/logout')
def logout():
    session.pop('username', None)  # 删除session
    flash('退出登录')  # 用于在下一个响应中显示一个消息。结合redirect使用，不能用render_template
    return redirect(url_for('account.login'))

    # session.pop("username")
    # response = make_response(render_template('account/login.html'))
    # response.delete_cookie('username')  # 删除cookie
    # return response
